package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.jdy.haoduoaiteacher.FileUtils;
import com.jdy.haoduoaiteacher.util.ImageUtils;
import com.jdy.haoduoaiteacher.util.LeXiaoXiaoBanLog;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//import com.jdy.haoduoaiteacher.R;

/**
 * Select picture from different resources.
 * 
 * @author zp @ 2015-6-9 下午5:14:15
 */
public class SelectPicPopupWindow extends BaseActivity implements
    OnClickListener {

  private final static String TAG = "SelectPicPopupWindow";

  @InjectView(id = R.id.btn_take_photo, click = true)
  private Button btn_take_photo;

  @InjectView(id = R.id.btn_pick_photo, click = true)
  private Button btn_pick_photo;

  @InjectView(id = R.id.btn_cancel, click = true)
  private Button btn_cancel;

  @InjectView(id = R.id.pop_layout)
  private LinearLayout layout;

  private static final int SELECT_PHOTO = 100;

  private static final int TAKE_PHOTO = 101;

  private static final int REQUEST_CROP = 102;

  private Uri mResultURI;

  private String mAvatarPath;

  // private Uri photoUri;
  // private final int CAMERA_WITH_DATA = 1;
  // private final int PHOTO_PICKED_WITH_DATA = 0;
  private final int INTENT_CROP = 2;
  private final int RESULT_FROM＿CAMERA = 3;

  private static final int PHOTO_PICKED_WITH_DATA = 1001;// 相册
  private static final int CAMERA_WITH_DATA = 1002;// 相机
  private static final int CROP_PHOTO = 101;
  private static final File PHOTO_DIR = new File(
      Environment.getExternalStorageDirectory() + "/CameraCache");
  private File mCurrentPhotoFile;// 照相机拍照得到的图片
  private File mCacheFile;
  private static String fileName;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image_selector);
    hideTitleView();
    mAvatarPath = "";
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      mAvatarPath = extras.getString("avatar_path", "");
    }

    layout.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        toastShow("提示：点击窗口外部关闭窗口！");
      }
    });
    btn_cancel.setOnTouchListener(new OnTouchListener() {
      @SuppressLint("ClickableViewAccessibility")
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          btn_cancel.getBackground().setColorFilter(0x99c7c7c7,
              android.graphics.PorterDuff.Mode.MULTIPLY);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          btn_cancel.getBackground().setColorFilter(null);
        }

        return false;
      }
    });
    btn_pick_photo.setOnTouchListener(new OnTouchListener() {
      @SuppressLint("ClickableViewAccessibility")
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          btn_pick_photo.getBackground().setColorFilter(0x99c7c7c7,
              android.graphics.PorterDuff.Mode.MULTIPLY);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          btn_pick_photo.getBackground().setColorFilter(null);
        }

        return false;
      }
    });

    btn_take_photo.setOnTouchListener(new OnTouchListener() {
      @SuppressLint("ClickableViewAccessibility")
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          btn_take_photo.getBackground().setColorFilter(0x99c7c7c7,
              android.graphics.PorterDuff.Mode.MULTIPLY);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          btn_take_photo.getBackground().setColorFilter(null);
        }

        return false;
      }
    });
  }

  /**
   * Destroy itself while click on empty space.
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    finish();
    return true;
  }

  // @Override
  // protected void onActivityResult(int requestCode, int resultCode,
  // Intent imageReturnedIntent) {
  // super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
  // switch (requestCode) {
  // case SELECT_PHOTO:
  // if (resultCode == RESULT_OK) {
  // this.mResultURI = imageReturnedIntent.getData();
  // startCrop(this.mResultURI);
  // }
  // break;
  // case TAKE_PHOTO:
  // if (resultCode == RESULT_OK) {
  // startCrop(this.mResultURI);
  // }
  // break;
  // case REQUEST_CROP:
  // if (resultCode == RESULT_OK) {
  // Bundle extras = imageReturnedIntent.getExtras();
  // if (extras != null) {
  // Bitmap photo = extras.getParcelable("data");
  // // The stream to write to a file or directly using the
  // try {
  // File tmpFile = createImageFile(true);
  // FileOutputStream fOut = new FileOutputStream(tmpFile);
  // photo.compress(Bitmap.CompressFormat.PNG, 100, fOut);
  // fOut.flush();
  // fOut.close();
  // setIntentResult(Uri.fromFile(tmpFile));
  // } catch (IOException e) {
  // // TODO Auto-generated catch block
  // e.printStackTrace();
  // }
  // finish();
  // }
  // }
  // }
  // }

  /**
   * 裁剪图片
   * 
   * @param uri
   */
  public void startPhotoZoom(Uri uri) {

    String fileName = System.currentTimeMillis() + ".jpg";
    if (!PHOTO_DIR.exists()) {
      PHOTO_DIR.mkdirs();// 创建照片的存储目录
    }
    mCacheFile = new File(PHOTO_DIR, fileName);
    Uri outputUri = Uri.fromFile(new File(mCacheFile.getPath()));
    String url = FileUtils.getPath(this, uri);

    Intent intent = new Intent("com.android.camera.action.CROP");
    // sdk>=24
    if (Build.VERSION.SDK_INT >= 24) {

      Uri imageUri = FileProvider.getUriForFile(this, "com.haoduoaiteacher.fileprovider",
          new File(url));// 通过FileProvider创建一个content类型的Uri
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
      intent.putExtra("noFaceDetection", true);// 去除默认的人脸识别，否则和剪裁匡重叠
      intent.setDataAndType(imageUri, "image/*");

      // 19=<sdk<24
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
        && Build.VERSION.SDK_INT < 24) {
      intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");

      // sdk<19
    } else {
      intent.setDataAndType(uri, "image/*");
    }
    intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
    intent.putExtra("aspectX", 19);// 这两项为裁剪框的比例.
    intent.putExtra("aspectY", 20);// x:y=1:2
    intent.putExtra("outputX", 600);
    intent.putExtra("outputY", 500);
    intent.putExtra("output", outputUri);
    intent.putExtra("outputFormat", "JPEG");// 返回格式
    startActivityForResult(intent, CROP_PHOTO);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_CANCELED) {
      return;
    }
    switch (requestCode) {
    case PHOTO_PICKED_WITH_DATA:// 相册返回
      Uri uri = data.getData();
      String selectedImagePath = FileUtils.getPath(this, uri);
      mCurrentPhotoFile = new File(selectedImagePath);
      startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
      break;
    case CAMERA_WITH_DATA:// 相机返回
      if (mCurrentPhotoFile == null || !mCurrentPhotoFile.exists()) {
        mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
      }

      startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
      break;
    case CROP_PHOTO:// 图片剪裁返回

      if (Tools.isNotEmpty(mCacheFile)) {
        Uri outputUri = Uri.fromFile(mCacheFile);
        Intent resultIntent = new Intent();
        resultIntent.putExtra("image", outputUri.toString());
        setResult(RESULT_OK, resultIntent);

        finish();
      }

      // addPictoList(url);

      break;
    }

    // switch (requestCode) {
    // case CAMERA_WITH_DATA: // 拍照
    // if (resultCode == RESULT_OK) {
    // try {
    // cropImageUriByTakePhoto();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    //
    // break;
    // case RESULT_FROM＿CAMERA:
    // if (resultCode == RESULT_OK) {
    // try {
    // if (mResultURI != null) {
    // setIntentResult(mResultURI);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // break;
    //
    // case PHOTO_PICKED_WITH_DATA:
    // if (resultCode == RESULT_OK) {
    //
    // if (Build.VERSION.SDK_INT < 19) {
    // try {
    // if (mResultURI != null) {
    // setIntentResult(mResultURI);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // } else {
    // Uri uri = data.getData();
    // String thePath = PhotoUtils.getInstance().getPath(this, uri);
    // PhotoUtils.getInstance().cropPicture(this,
    // Uri.fromFile(new File(thePath)));
    // }
    // }
    //
    // break;
    // case INTENT_CROP:
    // try {
    // if (data != null) {
    // Bitmap bitmap = data.getParcelableExtra("data");
    // if (bitmap != null) {
    // try {
    // File tmpFile = createImageFile(true);
    // FileOutputStream fOut = new FileOutputStream(tmpFile);
    // bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    // fOut.flush();
    // fOut.close();
    // setIntentResult(Uri.fromFile(tmpFile));
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // } else {
    // toastShow("选择照片失败");
    // }
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // break;
    // }
  }

  private void setIntentResult(Uri tmpFile) {
    LeXiaoXiaoBanLog.e(TAG, "set result");
    Intent resultIntent = new Intent();
    resultIntent.putExtra("image", tmpFile.toString());
    setResult(RESULT_OK, resultIntent);

    finish();
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_take_photo:
      // takePhoto();
      // doHandlePhoto(CAMERA_WITH_DATA);// 从相机获取

      String status = Environment.getExternalStorageState();
      if (status.equals(Environment.MEDIA_MOUNTED)) {
        if (!PHOTO_DIR.exists()) {
          PHOTO_DIR.mkdirs();// 创建照片的存储目录
        }
        fileName = System.currentTimeMillis() + ".jpg";
        mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
        Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (Build.VERSION.SDK_INT >= 24) {
          Uri imageUri = FileProvider.getUriForFile(this,
              "com.haoduoaiteacher.fileprovider", mCurrentPhotoFile);
          intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
          intentC.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        } else {
          intentC.putExtra(MediaStore.EXTRA_OUTPUT,
              Uri.fromFile(mCurrentPhotoFile));
        }
        startActivityForResult(intentC, CAMERA_WITH_DATA);
      } else {
        toastShow("没有SD卡");
      }

      break;
    case R.id.btn_pick_photo:
      // pickFromGallery();
      // doHandlePhoto(PHOTO_PICKED_WITH_DATA);// 从相册获取

      Intent intent = new Intent();
      intent.addCategory(Intent.CATEGORY_OPENABLE);
      intent.setType("image/*");
      if (Build.VERSION.SDK_INT < 19) {
        intent.setAction(Intent.ACTION_GET_CONTENT);
      } else {
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
      }
      startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);

      break;
    case R.id.btn_cancel:
      setCancelResult();
      break;
    default:
      break;
    }
    // finish();
  }

  private void setCancelResult() {
    Intent returnIntent = new Intent();
    setResult(RESULT_CANCELED, returnIntent);
    finish();
  }

  @SuppressWarnings("unused")
  private void pickFromGallery() {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");

    startActivityForResult(photoPickerIntent, SELECT_PHOTO);
    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
  }

  /**
   * Start crop editor after user has selected picture.
   * 
   * @param file
   */
  @SuppressWarnings("unused")
  private void startCrop(Uri file) {
    try {
      Uri targetFile = prepareCrop(file);
      mResultURI = targetFile;
      Intent intent = new Intent("com.android.camera.action.CROP");
      // intent.setClassName("com.android.camera",
      // "com.android.camera.CropImage");
      // intent.setData(file);
      intent.setDataAndType(targetFile, "image/*");
      intent.putExtra("crop", "true");
      intent.putExtra("scaleType", "centerCrop");
      intent.putExtra("aspectX", 1);
      intent.putExtra("aspectY", 1);
      intent.putExtra("outputX", 300);
      intent.putExtra("outputY", 300);
      intent.putExtra("noFaceDetection", true);
      intent.putExtra("return-data", true);
      startActivityForResult(intent, REQUEST_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
      // display an error message
      String errorMessage = "糟糕,您的设备不支持裁剪!";
      toastShow(errorMessage);
      setCancelResult();
    }
  }

  @SuppressWarnings("unused")
  private void takePhoto() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
      // Create the File where the photo should go
      File photoFile = null;
      try {
        photoFile = createImageFile(false);
      } catch (IOException ex) {
        ex.printStackTrace();
        // Error occurred while creating the File
      }
      // Continue only if the File was successfully created
      if (photoFile != null) {
        this.mResultURI = Uri.fromFile(photoFile);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, this.mResultURI);
        startActivityForResult(takePictureIntent, TAKE_PHOTO);
      }
    }
  }

  public Bitmap BITMAP_RESIZER(Bitmap bitmap, int newWidth, int newHeight) {
    Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight,
        Config.ARGB_8888);

    float ratioX = newWidth / (float) bitmap.getWidth();
    float ratioY = newHeight / (float) bitmap.getHeight();
    float middleX = newWidth / 2.0f;
    float middleY = newHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2,
        middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    return bitmap;

  }

  private Uri prepareCrop(Uri originalFileUri) {

    Bitmap b = ImageUtils.getBitmapFromUri(this, originalFileUri);

    // Matrix m = new Matrix();
    //
    // m.setRectToRect(new RectF(0, 0, b.getWidth(), b.getHeight()), new
    // RectF(0,
    // 0, 300, 300), Matrix.ScaleToFit.CENTER);
    //
    // Bitmap out = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m,
    // true);

    Bitmap out = BITMAP_RESIZER(b, 300, 300);// Bitmap.createScaledBitmap(b,
                                             // 300, 300, true);//

    FileOutputStream fOut;
    try {
      File file = createImageFile(false);
      fOut = new FileOutputStream(file);
      out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
      fOut.flush();
      fOut.close();
      b.recycle();
      out.recycle();
      return Uri.fromFile(file);
    } catch (Exception e) {

    }
    return null;
  }

  @SuppressLint("SimpleDateFormat")
  @SuppressWarnings("unused")
  private File createImageFile(boolean insideApp) throws IOException {
    // Create an image file name
    if (!insideApp) {
      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
          .format(new Date());
      String imageFileName = "PNG_" + "tmp" + "_";
      File storageDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

      if (!storageDir.exists()) {
        boolean ret = storageDir.mkdir();
        if (!ret) {
          storageDir.mkdirs();
        }
      }

      File image = File.createTempFile(imageFileName, /* prefix */
          ".png", /* suffix */
          storageDir /* directory */
      );

      // Save a file: path for use with ACTION_VIEW intents
      // galleryAddPic(image);// no need to add to the gallery!
      return image;
    } else {
      return new File(mAvatarPath);
    }
  }

  /**
   * Add to media center.
   */
  @SuppressWarnings("unused")
  private void galleryAddPic(File image) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File("file:" + image.getAbsolutePath());
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
  }

  private boolean isSDCARDMounted() {
    String status = Environment.getExternalStorageState();

    if (status.equals(Environment.MEDIA_MOUNTED)) {
      return true;
    }
    return false;
  }

  private Uri getTempUri() {
    Uri tempPhotoUri = Uri.fromFile(getTempFile());
    return tempPhotoUri;
  }

  private File getTempFile() {
    if (isSDCARDMounted()) {

      File f = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
      try {
        f.createNewFile();
      } catch (IOException e) {
        // ...
      }
      return f;
    }
    return null;
  }

  /**
   * 0-本地相册选择，非0为拍照
   * 
   * @param type
   */
  @SuppressLint("SimpleDateFormat")
  private void doHandlePhoto(int type) {
    try {
      // 保存裁剪后的图片文件
      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
          .format(new Date());
      String imageFileName = "PNG_" + "tmp" + "_";
      File pictureFileDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

      if (!pictureFileDir.exists()) {
        pictureFileDir.mkdirs();
      }

      File picFile = File.createTempFile(imageFileName, /* prefix */
          ".png", /* suffix */
          pictureFileDir /* directory */
      );

      if (!picFile.exists()) {
        picFile.createNewFile();
      }
      // mResultURI = Uri.fromFile(getTempFile());/* Uri.fromFile(picFile); */
      mResultURI = Uri.fromFile(picFile);

      if (type == PHOTO_PICKED_WITH_DATA) {
        Intent intent = getCropImageIntent();
        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
      } else {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mResultURI);
        startActivityForResult(cameraIntent, CAMERA_WITH_DATA);
      }

    } catch (Exception e) {
      Log.i("HandlerPicError", "处理图片出现错误");
    }
  }

  /**
   * 调用图片剪辑程序
   */
  @SuppressLint("InlinedApi")
  public Intent getCropImageIntent() {

    Intent intent = new Intent(Intent.ACTION_PICK, null);
    intent.setType("image/*");

    if (Build.VERSION.SDK_INT < 19) {
      setIntentParams(intent);
    } else {
      // TODO
    }

    return intent;

    // if (Build.VERSION.SDK_INT < 19) {
    // Intent intent = new Intent(Intent.ACTION_PICK, null);
    // intent.setType("image/*");
    // setIntentParams(intent);
    // return intent;
    // } else {
    // Intent intent = new Intent();
    // intent.setType("image/*");
    // // 由于Intent.ACTION_OPEN_DOCUMENT的版本是4.4以上的内容
    // // 所以注意这个方法的最上面添加了@SuppressLint("InlinedApi")
    // // 如果客户使用的不是4.4以上的版本，因为前面有判断，所以根本不会走else，
    // // 也就不会出现任何因为这句代码引发的错误
    // intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
    // setIntentParams(intent);
    //
    // return intent;
    // }
    // Intent intent = new Intent(Intent.ACTION_PICK, null);
    // intent.setType("image/*");
    // setIntentParams(intent);
    // return intent;
  }

  @SuppressWarnings("unused")
  private Bitmap decodeUriAsBitmap(Uri uri) {
    Bitmap bitmap = null;
    try {
      bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(
          uri));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    }
    return bitmap;
  }

  /**
   * 启动裁剪
   */
  private void cropImageUriByTakePhoto() {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(mResultURI, "image/*");
    setIntentParams(intent);
    startActivityForResult(intent, RESULT_FROM＿CAMERA);
  }

  /**
   * 设置公用参数
   */
  private void setIntentParams(Intent intent) {
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 600);
    intent.putExtra("outputY", 600);
    intent.putExtra("noFaceDetection", true); // no face detection
    intent.putExtra("scale", true);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mResultURI);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
  }

}
